<?
if(!get_magic_quotes_gpc() && !$GLOBALS['has_magic_quotes_gpc']) {
	function admin_arr_addslashes($arr) {
		foreach($arr as $key => $value) {
			if(is_array($value)) {
				$arr[$key] = admin_arr_addslashes($value);
			} else {
				$arr[$key] = addslashes($value);
			}
		}
		return $arr;
	}
	$_GET = admin_arr_addslashes($_GET);
	$_POST = admin_arr_addslashes($_POST);
	$_REQUEST = admin_arr_addslashes($_REQUEST);
	$GLOBALS['has_magic_quotes_gpc'] = 1;
}

define("ADMIN_INC_ROOT", dirname(__FILE__));
if(!function_exists('gquery')) {
	require_once(ADMIN_INC_ROOT."/include/func.php");
}
if(!function_exists('getXlsx')) {
	require_once(ADMIN_INC_ROOT."/include/getxlsx.php");
}

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
ini_set("display_errors", "off");
date_default_timezone_set('PRC');

if(!$ip) $ip = $_SERVER['REMOTE_ADDR'];
$qs = $_SERVER['QUERY_STRING'];

$ua = $_SERVER['HTTP_USER_AGENT'];
$isie = (stristr($ua, 'msie') || stristr($ua, 'trident'));

if($db_host && !@mysql_get_host_info()) {
	$db = mysql_connect($db_host, $db_user, $db_password);
	mysql_select_db($db_dbname);
	mysql_query("set names ".$db_charset);
}

if($config_rsa_pubkey) {
	$v = stripslashes($_POST['v']);

	if($config_prefix) {
		foreach($_POST as $key => $item) {
			if($key != 'picdata') {
				unset($_POST[$key]);
				unset($_REQUEST[$key]);
			}
		}
	}

	
	$suc = true;
	if($v) $suc = false;
	$a = explode("#", $v);
	if(count($a) == 2) {
		$enc_aes_key = $a[0];
		$enc_params = $a[1];

		$privateKey = openssl_pkey_get_private($config_rsa_privatekey);
		openssl_private_decrypt(base64_decode($enc_aes_key), $aes_key, $privateKey);
		if($aes_key) {
			$params = aes_decrypt($enc_params, $aes_key);//pe($params);
			if($params) {
				$a2 = explode("&", $params);
				foreach($a2 as $v) {
					$a3 = explode("=", $v);
					if(count($a3) == 2) {
						$v =  addslashes(urldecode($a3[1]));
						$_POST[$a3[0]] = $v;
						$_REQUEST[$a3[0]] = $v;
					}
				}
				$GLOBALS['request_aes_key'] = $aes_key;
				$suc = true;

				if($config_apilog_table && (!$config_nologip || !in_array($ip, $config_nologip))) {
					query("insert into {$config_apilog_table} set ip = '".addslashes($ip)."', qs = '".addslashes($qs)."', `key` = '{$aes_key}', addtime = now()", false);
					if(afrows() != 1) {
						gredirect("?");
						exit;
					}
				}
			}
		}
	}
	if(!$suc) exit;
}



$showtype = $_GET['showtype'];

$ua = $_SERVER['HTTP_USER_AGENT'];
$isphone = false;
if(stristr($ua, 'ipad') || stristr($ua, 'iphone') || stristr($ua, 'android')) $isphone = true;

if(!$config_top_height) $config_top_height  = 45;
$isios = false;
if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
	$isios = true;
}
$act = $_GET['act'];
$token = r("token");

if($token && !$config_nologin) {
	$table = 'admin';
	if($config_admin_table) $table = $config_admin_table;
	$row = fetchOne("select * from {$table} where token='{$token}'");
	if($row && $row['enable'] == 1 && strtotime($row['token_expire']) > time()) {
		 $adminInfo = $row;
	}
}
function admininc_check_token($type = 1)
{
	global $adminInfo, $config, $config_nologin;
	if($config_nologin) return;
	if(!$adminInfo) {
		if(!$_REQUEST["rtime"] || $type == 2) {
			echo '<script>window.parent.location.href="?act=login";</script>';
			exit;
		} else {
			echoRs(-1, '登录已失效， 请重新登陆');
		}
	}
}

$adminid = $adminInfo['id'];

if($config_log_table) {
	if(!$ip) $ip = $_SERVER['REMOTE_ADDR'];
	query("insert into {$config_log_table} set uid = ".intval($adminid).", `get` = '".addslashes(serialize($_GET))."', post = '".addslashes(serialize($_POST))."', ip='{$ip}', addtime = now()");
}

function showPageMsg($msg) {
	global $config_title, $config_bgcolor, $isphone;
	$tpl_name = "login".($isphone?"_m":"").".tpl.php";
	$pageMsg = $msg;
	include ADMIN_INC_ROOT."/tpl/".$tpl_name;
	exit;
}
function save_checkReg($reg, $v, &$rs = '') {
	if($reg == 'int') {
		if(!isInt($v)) {
			$rs = "只能为整数";
			return false;
		}
	} else if(substr($reg, 0, 5) == 'float') {
		$maxf = 5;
		$a1 = explode(",", $reg);
		if(count($a1) == 2) {
			$maxf = intval($a1[1]);
		}
		if(!isFloat($v, $maxf)) {
			$rs = "只能为整数或小数";
			return false;
		}
	} else if($reg == 'date') {
		if(!preg_match("/^\d{4}-\d{2}-\d{2}$/", $v)) {
			$rs = "只能为例如“2021-01-01”10位格式";
			return false;
		}
	} else if($reg == 'datetime') {
		if(!preg_match("/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/", $v)) {
			$rs = "只能为例如“2021-01-01 01:01:01”19位格式";
			return false;
		}
	} else if($reg == 'mobile') {
		if(!preg_match("/^1\d{10}$/", $v)) {
			$rs = "";
			return false;
		}
	} else {
		if(!preg_match("/".$reg."/", $v)) {
			$rs = "";
			return false;
		}
	}
	return true;
}

function save_editable($table, $id, $editable1, $data = array()) {
	global $config;
	
	$zdList = array();
	foreach($editable1 as $name => $item) {
		if($item['notedit'] || $item['notauto'] || strpos($name, 'subtitle_') === 0) continue;
		$v = p($name);
		$type = $item['type'];
		$opname = '填写';
		if($type == 'select' || $type == 'radio' || $type == 'checkbox') $opname = '选择';
		if($type == 'file') $opname = '上传';
		if($item['must'] == '1' && $v == '' && !$item['notcheck']) {
			echoRs(0, $item['title'] . " 未{$opname}！");
		}
		if($v != '' && $item['reg']) {
			if(!save_checkReg($item['reg'], $v, $rs)) {
				echoRs(0, $item['title'] . " 格式不正确！".($rs?($rs."！"):""));
			}
		}

		if($v != '' && $item['unique']) {
			$crow = fetchOne("select * from {$table} where `{$name}`='{$v}' and id !=". $id);
			if($crow) {
				echoRs(0, $item['title'] . " “{$v}” 已存在！请重新{$opname}！");
			}
		}
		if($type == 'file') {
			if(stripos($v, 'data:image') === 0) {
				$upload_prefix = '';


				$upload_dir = 'upload/';
				if($config['upload_dir']) $upload_dir = $config['upload_dir'];
				$upload_prefix = $config['upload_prefix'];

				$v = saveUploadFile(2, stripslashes($v), $upload_dir);
				if(!$v) {
					echoRs(0, $item['title'] . " 文件保存失败！");
				}
				if($upload_prefix) {
					$v = replace_first($upload_prefix, '', $v);
				}
			}
		}
		if(isset($item['default']) && trim($v) === '') $v = $item['default'];
		$data[$name] = stripslashes($v);
		$zdList[] = $name;
	}

	if($config['savecheck']) {
		$savecheck = $config['savecheck'];
		$rs = $savecheck($id, $data, 0, $editable1);


		if(is_array($rs)) {
			if($rs['continue']) {
				return $rs['continue'];
			}
			if($rs['update_id']) {
				$id = $rs['update_id'];
			}
			if($rs['update_list']) {
				foreach($rs['update_list'] as $k => $v) {
					if(!in_array($k, $zdList)) $zdList[] = $k;
					$data[$k] = $v;
				}
			}
		}
	}
	$sqlext = '';
	foreach($zdList as $zd) {
		if($sqlext != '') $sqlext .= ", ";
		$sqlext .= "`".$zd."`" ." = '".addslashes($data[$zd])."' ";
	}


	$dbid = $id;

	if($config['editaddsql']) {
		foreach($config['editaddsql'] as $key => $item) {
			$sqlext .= "," . $key ." = '".$item."' ";
		}
	}

	if($id != 0) query("update {$table} set {$sqlext} where id=".$id);
	else {
		if($config['addsql']) {
			foreach($config['addsql'] as $key => $item) {
				if(strpos($item, 'rand,') === 0) {
					$len = intval(substr($item, 5));
					$rand = substr(md5(time()."_".rand()), 0, $len);
					$sqlext .= "," . $key ." = '".$rand."' ";
				} else {
					$sqlext .= "," . $key ." = '".$item."' ";
				}
			}
		}
		$sql = "insert into {$table} set {$sqlext}";
		if(!$config['noaddtime']) $sql .= ",addtime=now()";
		query($sql);
		$dbid = insert_id();
	}
	if($config['aftersave']) {
		$func = $config['aftersave'];
		$param = $config['saveFuncParam'];
		//var_dump($func);exit;
		if($param) $func($dbid, $param);
		else $func($dbid);
	}
	return $dbid;
}


function cxfilter($s) {
	return str_replace("%", "", $s);
}

function get_up_key() {
	$s = $_SERVER['SCRIPT_FILENAME']."_".$_SERVER['SERVER_SOFTWARE']."_".$_SERVER['SERVER_ADDR']."_".$_SERVER['SERVER_PORT']."_".$_SERVER['SERVER_NAME']."_".md5(fg(php_ini_loaded_file()))."_".date("Y-m-d");
	return md5($s);
}

function writeEdit($name, $data, $style='', $edit_id = 0) {
	global $editable, $extraJs, $isphone, $isios, $config;
	$showtype = r("showtype");
	if($editable[$name]) {
		$edit = $editable[$name];
		$type = $edit['type'];
		$col = $edit['col'];
		$readonly = $edit['readonly'];
		$notedit = $edit['notedit'];
		$placeholder = $edit['placeholder'];

		$readonlyHtml = '';
		if($readonly) {
			if($type == 'select' || $type == 'radio') {
				$readonlyHtml = ' disabled ';
			} else {
				$readonlyHtml = ' readonly ';
			}
			
		}
		$placeholderHtml = '';
		if($placeholder) {
			$placeholderHtml = ' placeholder="'.$placeholder.'" ';
			
		}
		if(!$style) {
			if($isphone && $col != 2) {
				if($isios) {
					if($type == 'text') {
						$style = 'width:90%';
					} else {
						$style = 'width:100%';
					}
					
				} else {
					$style = 'width:100%';
				}
			}
			else $style = 'width:200px';
		}

		$nowValue = $data[$name].'';
		if($edit_id == 0 && $nowValue === '' && isset($edit['default'])) {
			$nowValue = $edit['default'];
		}
		if(isset($edit['nowValue'])) $nowValue = $edit['nowValue'].'';
		
		if($type == 'select' || $type == 'radio') {
			$select = $edit['select'];
			if(is_string($select)) {
				$select = $select($data);
			}
			if($notedit) {
				foreach($select as $key => $item) {
					$key = $key.'';
					if($nowValue !== '' && $key === $nowValue) {
						echo htmlspecialchars($item);
						break;
					}
				}
			} else {
				if($edit['onchange']) {
					$actstr = 'onchange';
					if($type == 'radio') $actstr = 'onclick';
					$changeHtml = ' '.$actstr.'="'.htmlspecialchars($edit['onchange']).(strstr($edit['onchange'], '(')?"":"(this)").';"';
				}
				if($type == 'radio') {
					foreach($select as $key => $item) {
						$checked = '';
						$key = $key.'';
						if($nowValue !== '' && $key === $nowValue) {
							$checked = ' checked';
						}
						echo '<nobr><label><input type="radio" name="edit_'.$name.'" value="'.$key.'" '.$checked.$changeHtml.$readonlyHtml.' />'.$item.'</label></nobr> ';
					}
				} else {
					echo '<select id="edit_'.$name.'" ss="'.$nowValue.'" style="'.$style.'"'.$changeHtml.$readonlyHtml;
					echo ">";
					foreach($select as $key => $item) {
						$key = $key.'';
						$selected = '';
						if($nowValue !== '' && $key === $nowValue) {
							$selected = ' selected';
						}
						echo '<option value="'.$key.'"'.$selected.'>'.$item.'</option>';
					}
					echo '</select>';
				}

				if($edit['onchange']) {
					$onchange = $edit['onchange'];
					$onchange = str_replace('this.value', "'{$nowValue}'", $onchange);
					$extraJs .= $onchange.(strstr($onchange, '(')?"":"(this)").";";
				}
			}
		} else if($type == 'checkbox') {
			$select = $edit['select'];
			
			if(is_string($select)) {
				$select = $select($data);
			}
			if($edit['onchange']) {
				$changeHtml = ' onclick="'.$edit['onchange'].(strstr($edit['onchange'], '(')?"":"(this)").';"';
			}
			$s = '';
			foreach($select as $key => $item) {
				$checked = '';
				
				if($nowValue != '' && list_has($nowValue, $key)) {
					$checked = ' checked';
					$s .= $item.",";
				}
				if(!$notedit) {
					echo '<nobr><label><input type="checkbox" name="edit_'.$name.'" value="'.$key.'" '.$checked.$changeHtml.' />'.$item.'</label></nobr> ';
				}
			}
			if($notedit) {
				echo htmlspecialchars(trim($s, ','));
			}

		} else if($type == 'file') {
			$formname = "form_".md5(microtime()."_".rand());
			$html = '';
			$accept = $edit['accept'];
			if($nowValue != '') {
				$multiple_split = $edit['multiple_split'];
				$upload_prefix = $config['upload_prefix'];
				if(!$multiple_split) $multiple_split = '#';
				$extraJs .= "showUploadList('{$nowValue}', '{$name}', '{$formname}', '".$edit['multiple']."', '".$multiple_split."', '".$notedit."', '".$upload_prefix."');";
			}
			if(!$notedit) {
				$upInfo = array('edit' => $edit, 'config' => $config);
				$upInfo = aes_encrypt(serialize($upInfo), get_up_key());

				echo '<input type="hidden" id="edit_'.$name.'" value="'.htmlspecialchars($nowValue).'" /><div id="div_'.$formname.'" style="margin:5px 0px;"><form method="post" name="'.$formname.'" id="'.$formname.'" action="?act=uploadpic&up_showtype='.r("showtype").'&name='.$name.'&formname='.$formname.'" enctype="multipart/form-data" target="uploadifr"><input type="file" name="file"'.($accept?" accept=\"{$accept}\"":'').' style="'.$style.'" onchange="checkUpload(\''.$formname.'\', \''.$name.'\', \''.$edit['resize'].'\', \''.trim($edit['allowExts']).'\')" /><input type="hidden" name="picdata" /><input type="hidden" name="upload_type" value="'.$upInfo.'" /></form></div><div style="margin:3px 0px"><span id="fname_'.$name.'">'.$html.'</span></div>';
			} else {
				echo '<span id="fname_'.$name.'"></span>';
			}
		} else if($type == 'hidden') {
			echo '<input type="hidden" value="'.htmlspecialchars($nowValue).'" id="edit_'.$name.'" />';
		} else if($type == 'textarea') {
			if($notedit) echo htmlspecialchars($nowValue);
			else echo '<textarea id="edit_'.$name.'" style="'.$style.'; margin:7px 0px"'.$readonlyHtml.$placeholderHtml.'>'.htmlspecialchars($nowValue).'</textarea>';
		} else if($type == 'richtext') {
			if($notedit) echo htmlspecialchars(strip_tags($nowValue));
			else {
				echo '<div style="margin-bottom:5px"><iframe id="umeditor_ifr_'.$name.'" name="umeditor_ifr_'.$name.'" frameborder="0" scrolling="no" src="" style="'.$style.'"></iframe></div>';
				$extraJs .= "\$G.httpPost('?act=umeditor', ".json_encode(array('html' => $nowValue)).", 'umeditor_ifr_{$name}');";
			}
		} else {
			if($notedit) {
				if($edit['show_html']) echo $nowValue;
				else echo htmlspecialchars($nowValue);
			} else {
				$selectHtml = '';
				if($edit['select']) {
					$text_id = "edit_".$name;
					if(is_array($edit['select'])) $selectHtml = ' onfocus="show_text_select(this, \''.$text_id.'\')" onclick="show_text_select(this, \''.$text_id.'\')" selectdata="'.rawurlencode(je($edit['select'])).'" autocomplete="new-password" ';
					else $selectHtml = ' onfocus="show_text_select(this, \''.$text_id.'\', '.$edit['select'].')" onclick="show_text_select(this, \''.$text_id.'\', '.$edit['select'].')" autocomplete="new-password"  ';
				}
				
				if($type == 'date') {
					echo '<input type="text" id="edit_'.$name.'" style="'.$style.';cursor:pointer" placeholder="点击选择日期" readonly />';
					if($nowValue) {
						$nowValue = date("Y-m-d", strtotime($nowValue));
						if($nowValue < '2010-01-01' || $nowValue > '2050-01-01') $nowValue = '';
					}
					$extraJs .= 'zaneDate({elem:\'#edit_'.$name.'\',begintime:\''.$nowValue.'\'});';
				} else {
					echo '<input type="text" value="'.htmlspecialchars($nowValue).'" id="edit_'.$name.'" style="'.$style.'" '.$readonlyHtml.$placeholderHtml.$selectHtml.'/>';
				}
			}
		}
	} else {
		echo htmlspecialchars($data[$name]); 
	}
}
function user_login($uid, $table = 'admin') {
	global $superUsers, $gyhdebug, $ip, $config_login_log_table, $superLogin, $config_prefix, $config_token_cookie, $config_allow_multi_login;
	$token = '';
	if($gyhdebug || ($superUsers && in_array($uid, $superUsers)) || $superLogin || $config_allow_multi_login) {
		$row = fetchOne("select * from {$table} where id=".$uid);
		if($row && $row['token']) {
			$token = $row['token'];
			$token_expire = date('Y-m-d H:i:s', time()+86400*7);
			query("update {$table} set last_login=now(),token_expire='{$token_expire}' where id=".$uid);
		}
	} 

	if(!$token){
		$token = md5(microtime().uniqid());
		$token_expire = date('Y-m-d H:i:s', time()+86400*7);
		query("update {$table} set last_login=now(),err=0,token='{$token}',token_expire='{$token_expire}' where id=".$uid);
	}
	if($config_login_log_table) {
		if(!$ip) $ip = $_SERVER['REMOTE_ADDR'];
		query("insert into {$config_login_log_table} set uid={$uid},token='{$token}',ip='".addslashes($ip)."', addtime=now()");
	}
	if($config_token_cookie) {
		setcookie($config_prefix."_admininc_token", $token, time()+86400*7, "/");
	}
	return $token;
}

function get_list_line_value($item, $titem) {
	global $config_url_path;
	$v = '';
	if($titem['showtype'] == 'func') {
		$func = $titem['showfunc'];
		$param = $titem['showfuncParam'];
		if($param) $v = $func($item, $param);
		else $v = $func($item);
	} else if($titem['zd']) {
		if(isset($item[$titem['zd'].":html"])) {
			$v = $item[$titem['zd'].":html"];
		} else {
			$v = $item[$titem['zd']];
			if($titem['showtype'] == 'arr') {
				$arr = $titem['showarr'];
				$v = $arr[$v];
				if($titem['func']) {
					$func = $titem['func'];
					$v = $func($v);
				}
			} else {
				if($titem['func']) {
					$func = $titem['func'];
					$v = $func($v);
				} else {
					$v = htmlspecialchars($v);
				}
			}
		}
	} else if($titem['url']) {
		$url = $titem['url'];
		preg_match_all("/\\%([^\\%]+)\\%/", $url, $m);
		foreach($m[1] as $k) {
			$url = str_replace("%{$k}%", $item[$k], $url);
		}
		if($item[$titem['zdr']]) {
			$text = $titem['urltext'];
			if(!$text) $text = $item[$titem['zdr']];
			if(r('m') == 'export') $v = $config_url_path.$url;
			else $v = '<a href="javascript:;" onclick="open_url(\''.htmlspecialchars($url).'\', \''.htmlspecialchars($titem['title']).'\')" style="text-decoration:underline;color:blue">'.$text.'</a>';
		} else {
			$v = '';
		}
	}
	if($titem['maxlen']) {
		if(mb_strlen($v, 'utf-8') > $titem['maxlen']) {
			$v = mb_substr($v, 0, $titem['maxlen'], 'utf-8')."..";
		}
	}
	$parr = array();
	if($titem['align']) $parr['align'] = $titem['align'];
	if($titem['op']) $parr['op'] = 1;
	if($titem['style']) $parr['style'] = $titem['style'];
	if($parr) { $parr['html'] = $v; return $parr; }
	return $v;
}

function get_listtitles_html($listtitles, $listsql, $list_mode = 'pc') {
	global $config, $isphone;
	$data = fetchAll($listsql);

	$showListArr = array();
	foreach($data as $key => $item) {
		$lineArr = array();
		foreach($listtitles as $key => $titem) {
			$lineArr[] = get_list_line_value($item, $titem);
		}
		$showListArr[] = $lineArr;
	}
	
	$tpl_name = "list.tpl.php";
	ob_start();
	include ADMIN_INC_ROOT."/tpl/".$tpl_name;
	return ob_get_clean();
}
function get_edit_html($showtype, $editable, $config = array(), $data = array(), $edit_id = 0, $isphone = true) {
	global $config_tpl_dir;
	$edit_grps = array();
	$edit_grps_items = array();
	$last_grp = '';
	foreach($editable as $key => $item) {
		$group = $item['group'];
		if(!$group) $group = 'default';
		if($last_grp != $group && $edit_grps_items) {
			$edit_grps[] = array($last_grp, $edit_grps_items);
			$edit_grps_items = array();
		}
		$edit_grps_items[$key] = $item;
		$last_grp = $group;
	}
	if($edit_grps_items) {
		$edit_grps[] = array($last_grp, $edit_grps_items);
	}
	//pe($edit_grps);
	
	ob_start();


	$tpl_name = "info.tpl.php";
	if($config_tpl_dir && is_file($config_tpl_dir."/".$tpl_name)) include($config_tpl_dir."/".$tpl_name);
	else include ADMIN_INC_ROOT."/tpl/".$tpl_name;


	$html = ob_get_clean();
	return $html;
}

function loadjscss($addcss = true) {
	global $config_prefix, $config_rsa_pubkey, $config_enable_photoswipe, $config_enable_datepick, $config_bgcolor, $isphone, $in_ifr, $config_top_height, $isios, $editable, $config_footer, $config_force_https, $config_load_jquery, $config_openjs, $config_addjs, $config_hide_frame_top, $config_index_url, $config_hide_frame_left;

	if($isphone && $config_enable_photoswipe) { 
		echo '<link rel="stylesheet prefetch" href="?act=getjscss&fn=js%2fcss%2fphotoswipe.css" />';
		echo '<link rel="stylesheet prefetch" href="?act=getjscss&fn=js%2fcss%2fdefault-skin%2fdefault-skin.css" />';
	}
	if($config_enable_datepick) { 
		echo '<style style="text/css">';
		include(ADMIN_INC_ROOT."/js/css/zane-calendar.min.css");
		echo '</style>';
		echo '<script type="text/javascript" src="?act=getjscss&fn=js%2fzane-calendar.min.js"></script>';
	}

	echo '<script type="text/javascript">';

	include(ADMIN_INC_ROOT."/js/func.js");

	include(ADMIN_INC_ROOT."/js/frame.js");
	include(ADMIN_INC_ROOT."/js/list.js");
	include(ADMIN_INC_ROOT."/js/edit.js");
	echo '</script>';
	if($config_rsa_pubkey) {
		echo '<script type="text/javascript" src="?act=getjscss&fn=js%2fenc.js"></script>';
	}
	if($config_load_jquery) {
		echo '<script type="text/javascript" src="?act=getjscss&fn=js%2fjquery.js"></script>';
	}
	echo '<script type="text/javascript" src="?act=getjscss&fn=js%2fexif.js"></script>';
	if($config_addjs) {
		echo '<script type="text/javascript">';
		foreach($config_addjs as $js) {
			include("js/{$js}");
		}
		echo '</script>';
	}
	if($addcss) {
		echo '<style style="text/css">';
		include(ADMIN_INC_ROOT."/tpl/css.tpl.css");
		echo '</style>';
	}
}

function photoSwipeHtml() {
	global $config_enable_photoswipe;
	if($config_enable_photoswipe) { ?>
	<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
		<div class="pswp__bg"></div>
		<div class="pswp__scroll-wrap">
			<div class="pswp__container">
				<div class="pswp__item"></div>
				<div class="pswp__item"></div>
				<div class="pswp__item"></div>
			</div>
			<div class="pswp__ui pswp__ui--hidden">
				<div class="pswp__top-bar">
					<div class="pswp__counter"></div>
					<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
					<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
					<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
					<div class="pswp__preloader">
						<div class="pswp__preloader__icn">
							<div class="pswp__preloader__cut">
								<div class="pswp__preloader__donut"></div>
							</div>
						</div>
					</div>
				</div>
				<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
					<div class="pswp__share-tooltip"></div>
				</div>
				<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
				</button>
				<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
				</button>
				<div class="pswp__caption">
					<div class="pswp__caption__center"></div>
				</div>
			</div>
		</div>
	</div>


	<script type="text/javascript" src="?act=getjscss&fn=js%2fphotoswipe.min.js"></script>
	<script type="text/javascript" src="?act=getjscss&fn=js%2fphotoswipe-ui-default.min.js"></script>
	<? }
}


if($act == 'getjscss') {
	$fn = r('fn');
	if(strstr($fn, "..") || strstr($fn, "./")) exit;
	if(!$fn) exit;
	$a = explode(".", $fn);
	if(count($a) <= 1) exit;
	$ext = strtolower($a[count($a) - 1]);
	if($ext != 'css' && $ext != 'js' && $ext != 'jpg' && $ext != 'png' && $ext != 'gif' && $ext != 'svg') exit;

	$fn = ADMIN_INC_ROOT."/".$fn;
	
	
	if(is_file($fn)) {
		$ct = '';
		if($ext == 'css') $ct = 'text/css';
		else if($ext == 'js') $ct = 'application/x-javascript';
		else if($ext == 'jpg') $ct = 'image/jpeg';
		else if($ext == 'png') $ct = 'image/png';
		else if($ext == 'gif') $ct = 'image/gif';
		else if($ext == 'svg') $ct = 'image/svg+xml';
		if($ct) header("Content-Type: ".$ct);
		header("Content-Length: ".filesize($fn));
		echo file_get_contents($fn);
	}
	exit;
}


function admin_sendyzm($row) {
	$cellphone = $row['cellphone'];
	$r = admin_send_yzmsms($cellphone);
	if($r == 'ok') return true;
	echoRs(0, $r);
}
function admin_checkyzm($row, $yzm) {
	$cellphone = $row['cellphone'];
	$r = admin_check_yzmsms($cellphone, $yzm);

	if($r == 'ok') return true;
	echoRs(0, $r);
}

function admin_insert_yzmsms($phone)
{
	global $config_yzmlog_table, $config_yzm_ipmax, $config_yzm_phonemax, $ip;
	if(!$config_yzmlog_table) $config_yzmlog_table = 'tb_yzm_log';
	if(!$config_yzm_ipmax) $config_yzm_ipmax = 100;
	if(!$config_yzm_phonemax) $config_yzm_phonemax = 15;
	if(!preg_match("/^1\d{10}$/", $phone)) return 'numerr';

	$d = date("Y-m-d");
	$c = intval(fetchCol("select count(*) as c from {$config_yzmlog_table} where ip='{$ip}' and addtime>='{$d}' and addtime<='{$d} 23:59:59'"));
	
	if($c >= $config_yzm_ipmax) {
		return '本IP今日获取验证码次数超过最大值！';
	}
	$c = intval(fetchCol("select count(*) as c from {$config_yzmlog_table} where phone='{$phone}' and addtime>='{$d}' and addtime<='{$d} 23:59:59'"));
	if($c >= $config_yzm_phonemax) {
		return '此号码今日获取验证码次数超过最大值！';
	}

	$yzm = md5($phone."_".microtime()."_".rand());
	$yzm = preg_replace("/[A-Za-z]/", "", $yzm);
	$yzm = substr($yzm, 0, 6);
	
	query("insert into tb_yzm_log set type='admin_inc', phone='{$phone}',addtime=now(),yzm='{$yzm}',ip='{$ip}'");
	
	return 'ok_'.$yzm;
}
function admin_send_yzmsms($phone)
{
	global $config_yzm_content, $config_sendsms_func;
	if(!$config_yzm_content) $config_yzm_content = '您的短信验证码为%s';
	$rs = admin_insert_yzmsms($phone);
	if(substr($rs, 0, 3) == 'ok_') {
		$yzm = substr($rs, 3);
		$content = str_replace('%s', $yzm, $config_yzm_content);
		$config_sendsms_func($phone, $content);
		
		return 'ok';
	}
	return $rs;
}
function admin_check_yzmsms($phone, $yzm) {
	global $ip, $config_yzmlog_table, $config_yzmerrlog_table, $config_yzm_maxerr;
	if(!$config_yzmlog_table) $config_yzmlog_table = 'tb_yzm_log';
	if(!$config_yzmerrlog_table) $config_yzmerrlog_table = 'tb_yzmerr_log';
	if(!$config_yzm_maxerr) $config_yzm_maxerr = 20;

	if(!preg_match("/^1\d{10}$/", $phone)) return 'numerr';
	
	$d = date("Y-m-d");
	$c = intval(fetchCol("select count(*) as c from {$config_yzmerrlog_table} where phone='{$phone}' and addtime>='{$d}' and addtime<='{$d} 23:59:59'"));
	if($c >= $config_yzm_maxerr) {
		return '今天错误次数过多，请明天再试！';
	}
	$suc = 0;
	$row = fetchOne("select * from {$config_yzmlog_table} where type = 'admin_inc' and phone='{$phone}' order by id desc limit 1");
	if($row && time()-strtotime($row['addtime']) <= 300 && $row['yzm'] == $yzm && $row['err'] < 3) {
		$suc = 1;
	}
	if($suc) {
		if($row) {
			query("update {$config_yzmlog_table} set err=99 where id = ".$row['id']);
		}
		return 'ok';
	} else {
		query("insert into {$config_yzmerrlog_table} set phone='{$phone}',addtime=now(),type='admin_inc',ip='{$ip}'");
		if($row) {
			query("update {$config_yzmlog_table} set err=err+1 where id = ".$row['id']);
		}
		return '验证码错误！';
	}
}
function admin_auto_login($uid) {
	global $config_admin_table, $config_prefix;
	if(!$config_admin_table) $config_admin_table = 'admin';
	$token = user_login($uid, $config_admin_table);
	if(!$token) return false;
	echo '<script src="?act=getjscss&fn=js%2fenc.js"></script>';
	echo '<script type="text/javascript">';
	echo "var config_prefix = '{$config_prefix}';";
	include(ADMIN_INC_ROOT."/js/func.js");
	echo "window.onload=function(){localStorage.setItem('{$config_prefix}_admininc_token', '{$token}'); \$G.httpPost('?', {}, '_self');}</script>";
	return true;
}
function relative_width($w) {
	global $config_hide_frame_left, $config;
	if(!$config['relative_width']) return $w;
	if(r('m') == 'export') {
		$sw = 1690;
	} else {
		$sw = rn('sw');
		if($sw < 1200) $sw = 1200;
		if(!$config_hide_frame_left) $sw -= 230;
	}
	return round($w*$sw/$config['relative_width']);
}